package com.example.dell.fastshopping.mall;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.dell.fastshopping.product.ProductActivity;
import com.example.dell.fastshopping.R;
import com.example.dell.fastshopping.loginRegist.LoginActivity;
import com.example.dell.fastshopping.mall.entity.DuoBaoMenu;
import com.example.dell.fastshopping.mall.entity.HeadTab;
import com.example.dell.fastshopping.mall.model.DuoBaoMenuViewModel;
import com.example.dell.fastshopping.user.entity.UserInfo;
import com.example.dell.fastshopping.utils.GlideUtils;
import com.example.dell.fastshopping.utils.KLog;
import com.example.dell.fastshopping.utils.SPDao;
import com.example.dell.fastshopping.utils.ToastUtils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoaderInterface;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class DuoBaoMenuFragment extends Fragment {

    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.home_type_container)
    LinearLayout homeTypeContainer;
    @BindView(R.id.zero_title)
    TextView zeroTitle;
    @BindView(R.id.zero)
    RelativeLayout zero;
    @BindView(R.id.one_title)
    TextView oneTitle;
    @BindView(R.id.one)
    FrameLayout one;
    @BindView(R.id.tow_tile)
    TextView towTile;
    @BindView(R.id.two)
    FrameLayout two;
    @BindView(R.id.three_title)
    TextView threeTitle;
    @BindView(R.id.three)
    FrameLayout three;
    @BindView(R.id.four_title)
    TextView fourTitle;
    @BindView(R.id.four)
    FrameLayout four;
    @BindView(R.id.right)
    LinearLayout right;
    @BindView(R.id.left_pic)
    ImageView left_pic;
    private DuoBaoMenuViewModel mViewModel;
    private Unbinder bind;
    private Context context;

    public static DuoBaoMenuFragment newInstance() {
        return new DuoBaoMenuFragment();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.main_fragment, container, false);
        bind = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(DuoBaoMenuViewModel.class);
        initView();
    }

    private void initView() {
        ArrayList<Integer> bannerList = mViewModel.getBannerList();
        //设置图片网址或地址的集合
        banner.setImages(bannerList);
        //设置轮播间隔时间
        banner.setDelayTime(3000);
        //设置是否为自动轮播，默认是“是”。
        banner.isAutoPlay(true);
        banner.setBannerStyle(BannerConfig.CENTER);
        //设置轮播的动画效果，内含多种特效，可点入方法内查找后内逐一体验
        banner.setBannerAnimation(Transformer.Default);
        banner.setImageLoader(new ImageLoaderInterface() {
            @Override
            public void displayImage(Context context, Object path, View imageView) {
                Glide.with(context).load(path).centerCrop().into((ImageView) imageView);
            }

            @Override
            public View createImageView(Context context) {
                return null;
            }
        });
        //设置指示器的位置，小点点，左中右。
        banner.setIndicatorGravity(BannerConfig.CENTER)
                //以上内容都可写成链式布局，这是轮播图的监听。比较重要。方法在下面。
                .setOnBannerListener(new OnBannerListener() {
                    @Override
                    public void OnBannerClick(int position) {
                    }
                })
                .start();//必须最后调用的方法，启动轮播图。

        getHeadTab();
        mViewModel.getList().observe(this, new Observer<List<DuoBaoMenu>>() {
            @Override
            public void onChanged(@Nullable List<DuoBaoMenu> duoBaoMenuList) {
                for (int i = 0; i < duoBaoMenuList.size(); i++) {
                    DuoBaoMenu duoBaoMenu = duoBaoMenuList.get(i);
                    switch (i) {
                        case 0:
                            zeroTitle.setText(duoBaoMenu.getGradeName());
                            zero.setTag(duoBaoMenu.getId());
                            break;
                        case 1:
                            oneTitle.setText(duoBaoMenu.getGradeName());
                            one.setTag(duoBaoMenu.getId());
                            break;
                        case 2:
                            towTile.setText(duoBaoMenu.getGradeName());
                            two.setTag(duoBaoMenu.getId());
                            break;
                        case 3:
                            threeTitle.setText(duoBaoMenu.getGradeName());
                            three.setTag(duoBaoMenu.getId());
                            break;
                        case 4:
                            fourTitle.setText(duoBaoMenu.getGradeName());
                            four.setTag(duoBaoMenu.getId());
                            break;
                        default:
                            break;
                    }

                }
            }
        });

        right.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int height = right.getHeight();
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) left_pic.getLayoutParams();
                layoutParams.height = height;
                left_pic.setLayoutParams(layoutParams);
            }
        });
    }

    private void getHeadTab() {
        final LayoutInflater inflater = LayoutInflater.from(context);
        mViewModel.getHeadTable().observe(this, new Observer<List<HeadTab>>() {
            @Override
            public void onChanged(@Nullable List<HeadTab> headTabs) {
                for (HeadTab h : headTabs) {
                    View view = inflater.inflate(R.layout.home_duobao_item, homeTypeContainer, false);
                    ImageView icon = view.findViewById(R.id.icon);
                    GlideUtils.setView(context, h.getPic(), icon);
                    TextView name = view.findViewById(R.id.name);
                    name.setText(h.getLabel());
                    view.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            goProductPage();
                        }
                    });
                    homeTypeContainer.addView(view);
                }
            }
        });

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        bind.unbind();
    }

    //现在的逻辑是只要交了某场次的保证金 就可以进入
    private void checkPermission(int id) {
        List<UserInfo.Amounts> amountsList = SPDao.getAmountsList();
        if (id == 1) {//1是体验场 放过
            Intent intent = new Intent(context, DuoBaoMallActivity.class);
            intent.putExtra("id", id);
            startActivity(intent);
            return;
        }
        for (UserInfo.Amounts entity : amountsList) {
            if (entity.getId() == id) {
                double amount = entity.getAmount().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                if (entity.getAmount() != null && amount > 0) {
                    if (amount < Double.valueOf(entity.getVal())) {
                        ToastUtils.showShort("当前专场保证金不足,请尽快缴纳");
                        return;
                    }
                    Intent intent = new Intent(context, DuoBaoMallActivity.class);
                    intent.putExtra("id", id);
                    startActivity(intent);
                } else {
                    ToastUtils.showShort("该场次需提交保证金");
                }
            }
        }
    }

    @OnClick({R.id.zero, R.id.one, R.id.two, R.id.three, R.id.four})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.zero:
                toDuoBaoMallActivity(view.getTag());
                break;
            case R.id.one:
                toDuoBaoMallActivity(view.getTag());
                break;
            case R.id.two:
                toDuoBaoMallActivity(view.getTag());
                break;
            case R.id.three:
                toDuoBaoMallActivity(view.getTag());
                break;
            case R.id.four:
                toDuoBaoMallActivity(view.getTag());
                break;
        }
    }

    private void toDuoBaoMallActivity(Object tag) {
        boolean isFirst = SPDao.getShouldLogin();
        if (isFirst) {
            KLog.e("login");
            Intent intent = new Intent(context, LoginActivity.class);
            startActivity(intent);
        } else if (tag != null) {
            checkPermission((int) tag);
        }
    }

    private void goProductPage() {
        Intent intent = new Intent(context, ProductActivity.class);
        startActivity(intent);
    }
}
